package com.zc.gateway.security.handler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.zc.commons.auth.exception.AnonymousAccessDeniedException;
import com.zc.commons.http.entity.Response;
import com.zc.commons.http.enums.RespCode;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.server.authorization.ServerAccessDeniedHandler;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 接口权限失败处理
 */
@Component
public class RoleAccessDeniedHandler implements ServerAccessDeniedHandler {
    @Override
    public Mono<Void> handle(ServerWebExchange serverWebExchange, AccessDeniedException e) {
        ServerHttpResponse response = serverWebExchange.getResponse();
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
        HttpStatus httpStatus = HttpStatus.FORBIDDEN;
        RespCode respCode = RespCode.FORBIDDEN;
        // 禁止匿名访问  需要提示登录
        if (e instanceof AnonymousAccessDeniedException) {
            httpStatus = HttpStatus.UNAUTHORIZED;
            respCode = RespCode.UNAUTHORIZED;
        }
        response.setStatusCode(httpStatus);
        Response<String> respData = Response.error(respCode, e.getMessage());
        DataBuffer buffer = response.bufferFactory().wrap(JSON.toJSONString(respData, SerializerFeature.WriteMapNullValue).getBytes());
        return response.writeWith(Mono.just(buffer));
    }
}
